from datetime import timedelta
from app.pkg.oss_ops import OssHandler
from flask import Flask, current_app, g, jsonify, request
from app.common.logger.customlogger import CustomLogger
# from app.common.minio.operate import MinioDb
from app.config import OperateYaml
from app.routes.oss_route import oss_routes


def create_app(loader):
  app = Flask(__name__)
  print(loader)
  #初始化日志
  logger = CustomLogger(loader['logger']['dir'], loader['logger']['level']).getLogHandler()
  app.logger.addHandler(logger)
  # app.config["JWT_SECRET_KEY"] = loader['JWT_SECRET_KEY']
  # app.config["JWT_VERIFY_SUB"]= loader['JWT_VERIFY_SUB']
  # app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=loader['JWT_ACCESS_TOKEN_EXPIRES'])
  # app.config['DATA_DIR'] = loader['data_dir']
  # jwt = JWTManager(app)

  # minio 客户端初始化
  ossHandler = OssHandler(loader['aliyun']['access_key'],loader['aliyun']['secret_key'],loader['aliyun']['bucket_name'],loader['aliyun']['endpoint'])

  # 请求前的处理
  @app.before_request
  def log_request_info():
    ip = request.remote_addr
    method = request.method
    url = request.url
    body = request.get_data() if request.is_json else request.form.to_dict() if request.form else {}
    app.logger.info(f"Request:[client_ip:{ip}-method:{method}-url:{url}-body:{body}]")

  @app.before_request
  def before_request():
    g.OssHandler = ossHandler
    # g.file_client = file_client

  app.register_blueprint(oss_routes, url_prefix='/oss')
  # 可以通过 app.config 传递配置
  # app.config.from_object('config.Config')

  return app